<?php 
class Tenpay{
	
 	/* 商户号 */
	private $bargainor_id = "";

	/* 密钥 */
	private $key = "";
	
	/* 返回处理地址 */
	private $return_url = "";
	
	private $reqHandler;
	private $reqHandler1;
	
	public function __construct(){
		require_once ("payment/tenpay/PayRequestHandler.class.php");
		require_once ("payment/tenpay/PayResponseHandler.class.php");
		$payment = M('Payment');
		$data = $payment->find(4);
		$this->bargainor_id = $data['business'];
		$this->key = $data['key'];
		$reqHandler = new PayRequestHandler();
		$reqHandler->init();
		$reqHandler->setKey($this->key);
		$resHandler1 = new PayResponseHandler();
		$resHandler1->setKey($this->key);
		
		$this->return_url = HOST.__APP__.'/Payment/tenpay_return_url';
		$this->reqHandler = $reqHandler;
		$this->reqHandler1 = $resHandler1;
	}
	
	public function _return_url(){
		//判断签名
		if($this->reqHandler1->isTenpaySign()) {			
			//支付结果
			$pay_result = $this->reqHandler1->getParameter("pay_result");
			
			if( "0" == $pay_result ) {
				return true;			
			} else {
				//当做不成功处理
				return false;
			}
			
		} else {
			return false;
		}
	}
	
	/*$data 为数组
	 * RE
	 * ['sn']定单号
	 * ['amount'] 订单价格
	 * 
	 * PA
	 * ['ordersn']定单号
	 * ['goodsname']商品名称
	 * ['remark']商品描述
	 * ['orderprice'] 订单价格
	 * 
	 * $type 为订单类型 RE充值 PA支付
	 * */
	public function _alipayto($data,$type='RE'){
		/*以下参数是需要通过下单时的订单数据传入进来获得*/
		
		//date_default_timezone_set(PRC);
		$strDate = date("Ymd");
		$strTime = date("His");
		
		//4位随机数
		$randNum = rand(1000, 9999);
		
		//10位序列号,可以自行调整。
		$strReq = $strTime . $randNum;

		/* 财付通交易单号，规则为：10位商户号+8位时间（YYYYmmdd)+10位流水号 */
		$transaction_id = $this->bargainor_id . $strDate . $strReq;
		
		//必填参数
		if ($type == 'RE'){
			$config = C('SYSCONFIG');
			$beat = $data['amount'] * $config['rmb_beat'];
			$sp_billno = $data['sn'];		//请与贵网站订单系统中的唯一订单号匹配
			$total_fee    = $data['amount'];	//订单总金额，显示在支付宝收银台里的“应付总额”里
		}elseif ($type == 'PA'){
			$sp_billno = $data['ordersn'];		//请与贵网站订单系统中的唯一订单号匹配
			$total_fee    = $data['orderprice'];	//订单总金额，显示在支付宝收银台里的“应付总额”里
		}
		
		$this->reqHandler->setParameter("bargainor_id", $this->bargainor_id);			//商户号
		$this->reqHandler->setParameter("sp_billno", $sp_billno);					//商户订单号
		$this->reqHandler->setParameter("transaction_id", $transaction_id);		//财付通交易单号
		$this->reqHandler->setParameter("total_fee", $total_fee*100);					//商品总金额,以分为单位
		$this->reqHandler->setParameter("return_url", $this->return_url);				//返回处理地址
		$this->reqHandler->setParameter("desc", "订单号：" . $transaction_id);	//商品名称
		
		//用户ip,测试环境时不要加这个ip参数，正式环境再加此参数
		$this->reqHandler->setParameter("spbill_create_ip", $_SERVER['REMOTE_ADDR']);
		$sHtmlText = $this->reqHandler->getRequestURL();
		return $sHtmlText;
	}	
	
}
?>